<?php
// +----------------------------------------------------------------------+
// | Author:  Evgeny Leontev <eleontev@gmail.com>                         |
// | Copyright (c) 2005 Evgeny Leontev                                    |
// +----------------------------------------------------------------------+
// | This source file is free software; you can redistribute it and/or    |
// | modify it under the terms of the GNU Lesser General Public           |
// | License as published by the Free Software Foundation; either         |
// | version 2.1 of the License, or (at your option) any later version.   |
// |                                                                      |
// | This source file is distributed in the hope that it will be useful,  |
// | but WITHOUT ANY WARRANTY; without even the implied warranty of       |
// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU    |
// | Lesser General Public License for more details.                      |
// +----------------------------------------------------------------------+

class CalendarUtil {
	
	var $lang = 'en';					// month will be generated in this lang
	var $sek_in_day = '86400';
	var $day;
	var $month;
	var $year;
	var $week;
	var $week_start = 1;				// 0 - for Sunday, 1 - for Monday
    var $cur_day = array();
	var $show_other_days = 1;			// show or not days for not current month
	
	//var $weekday_name = Array(1 => 'Sun','Mon','Tue','Wed','Thu','Fri','Sat'); // for inside purpose 
	
	var $month_format = '%B';			// format for month value 
										// %B - full month name
										// %b - abbreviated month name 
										// %m - month as a decimal number (range 01 to 12) 
	
	var $week_day_format = '%A';		// %A - full weekday name according to the current locale 
										// %a - abbreviated weekday name according to the current locale 
										


	function CalendarUtil($lang = false) {
		$lang = ($lang) ? $lang : $this->lang;
		$this->setLang($lang);
	}
	
	
	function setLang($lang) {
		setlocale(LC_TIME, $lang);
	}
	
	
	
	
   /**
	* setCalendar -- set all nesessary calendar values
	*
	* @param    mixed   $timestamp    (optional) one param (UNIXTEMISTAMP) or 3 param (day, month, year)
	*
	* @return   void
	* @access   public    
	*/
	function setCalendar($timestamp = false) {
	
		$numargs = func_num_args();
		if($numargs > 1) { 
			$arg_list = func_get_args();
			$this->day = $arg_list[0];
			$this->month = $arg_list[1];
			$this->year = $arg_list[2];
		} else {
			if(!$timestamp) { $timestamp = time(); }

			$this->day = date('j', $timestamp);
			$this->month = date('n', $timestamp);
			$this->year = date('Y', $timestamp);
		}
		
		$this->setCalendarValues();
	}
	
	
	// int mktime ( int hour, int minute, int second, int month, int day, int year [, int is_dst])
	// not sure is it right way, but it's working!
	function _setWeekDays() {
		for($i=0;$i<7;$i++){
			$week_days['week_day_'.$i] = ucfirst(strftime($this->week_day_format, mktime(0,0,0,2,22+$this->week_start+$i,2004)));
		}
		return $week_days;
	}
	
/*
	function _setMonthNames() {
		for($i=1;$i<=12;$i++){
			$month_names[] = ucfirst(strftime($this->month_format, mktime(0,0,0,$i,1,2004));
		}
		return $month_names;
	}
*/
	
	

	function setCalendarValues() {
	
		$this->month_name = strftime($this->month_format, mktime(0,0,0,$this->month,1,$this->year));
		$this->cur_month_num_days = strftime('%d', mktime(0,0,0,$this->month+1,0,$this->year));
		$this->prev_month_num_days = strftime('%d', mktime(0,0,0,$this->month,0,$this->year));
		$this->prev_month = $this->getPrevNextMonth($this->month, 'prev');
		$this->next_month = $this->getPrevNextMonth($this->month, 'next');
		$this->month_start_day = date('D', mktime(0,0,0,$this->month,1,$this->year));
		
		$this->prev_year = $this->getPrevNextYear($this->month, $this->year, 'prev');
		$this->next_year = $this->getPrevNextYear($this->month, $this->year, 'next');
		
		$this->week_cur_day = date('D', mktime(0,0,0,$this->month,$this->day,$this->year));
		$this->week_days = $this->_setWeekDays($this->month, $this->year);
	}
	
	
	
	function getPrevNextMonth($month, $what) {
		if($what == 'prev') {
			if($month == 1) { $n_month = 12; } 
			else            { $n_month = $month-1; }
		} else {
			if($month == 12) { $n_month = 1; } 
			else             { $n_month = $month+1; }
		}
		
		return $n_month;
	}
	
	
	// return next or previos year
	function getPrevNextYear($month, $year, $what) {
		if($what == 'prev') {
			if($month == 1) { $n_year = $year-1; } 
			else            { $n_year = $year; }
		} else {
			if($month == 12) { $n_year = $year+1; } 
			else             { $n_year = $year; }
		}
		
		return $n_year;
	}
	
	
   
   
   /**
	* isToday -- check for today 
	*
	* @param    mixed   $timestamp    (optional) one param (UNIXTEMISTAMP) or 3 param (day, month, year)
	*
	* @return   void
	* @access   public    
	*/
	function isToday($timestamp) {
		
		$today = false;
/*
		$numargs = func_num_args();
		if($numargs > 1) { 
			$arg_list = func_get_args();
			$day = $arg_list[0];
			$month = $arg_list[1];
			$year = $arg_list[2];
		
			if($day == date('d') && $month == date('m') && $year == date('Y')) {
				$today = true;
			}
		
		} else {
*/
			if(date('Ymd') == date('Ymd', $timestamp)) {
				$today = true;
			}
		//}
		return $today;
	}

	
	function isCurrentMonth($timestamp) {
		if(date('m', $timestamp) == $this->month) { return true; }
		else                                      { return false; }
	}
	
	
	// add 0 at numbers < 10
	function prepareNum($num) {
		if($num<10) { $num = 0 . $num; }
		return $num;
	} 
	
	
	// return day, month, year
	function fromTimestamp($timestamp) {
		$this->data['day'] = date('j', $timestamp);
		$this->data['month'] = date('n', $timestamp);
		$this->data['year'] = date('Y', $timestamp);
		
		return $this->data;
	}
	
	
	function _getOffset($start_day, $week_start = 0) {
		$timestamp = mktime(0,0,0,2,22+$week_start,2004);
		for($i=0;$i<7;$i++){
			$offset = date('D', $timestamp+86400*$i);
			$offsets[$offset] = $i;
			
		}
		return $offsets[$start_day];
	}
	
	
	// generate week values
	function setWeek() {
		$offset = $this->_getOffset($this->week_cur_day, $this->week_start);
		$start = ($offset) ? $this->sek_in_day*$offset : 0; // what to minus (timestamp) or 0
		$week_start_timestamp = mktime(1,0,0,$this->month,$this->day,$this->year) - $start; // week start timestamp
		
		$this->data['prev'] = $week_start_timestamp - $this->sek_in_day*7;
		$this->data['next'] = $week_start_timestamp + $this->sek_in_day*7;
		$this->data['start_day'] = $week_start_timestamp;
		$this->data['end_day'] = $week_start_timestamp + $this->sek_in_day*6;
		
		return $this->data;
	}
	
	
	// generate month values
	function & setMonth() {
	
		$offset = $this->_getOffset($this->month_start_day, $this->week_start);
		
		if($offset > 0) {
			$day = $this->prev_month_num_days-$offset+1; // 25
			$month = $this->prev_month;
			$year = ($this->month == 1) ? $this->prev_year : $this->year;
		} else {
			$day = 1; $month = $this->month; $year = $this->year;
		}
		
		$this->data['start_day'] = mktime(0,0,0,$month,$day,$year);
		$this->data['prev'] = mktime(0,0,0,$this->prev_month,1,$year);
		
		
		$num_days = $this->cur_month_num_days + $offset; // days all
		if($num_days == 28)     { $outset = 0;              $this->data['num_weeks'] = 4; } 
		elseif($num_days > 35)  { $outset = 42 - $num_days; $this->data['num_weeks'] = 6; } 
		else                    { $outset = 35 - $num_days; $this->data['num_weeks'] = 5; }
		
		
		if($outset > 0) {
			$day = $outset;
			$month = $this->next_month;
			$year = ($this->month == 12) ? $this->next_year : $this->year;
		} else {
			$day = 1; $month = $this->month; $year = $this->year;
		}
		
		$this->data['end_day'] =  mktime(0,0,0,$month,$day,$year);
		$this->data['next'] = mktime(0,0,0,$this->next_month,1,$year);
		
		return $this->data;

	}
	
}



class CalendarOutput extends CalendarUtil
{
	
	
	function dayView() {
		
	}
	
	
	function weekView() {
		
	}
	
	
	function monthView() {
		$num = 0;
		$tpl = new tplTemplatez('../tmpl/month_view.html');
		$tpl->tplAssign('td_height', 90/$this->data['num_weeks'].'%'); // td can vary
		
		for($i=1;$i<=$this->data['num_weeks'];$i++){
			
			for($j=1;$j<=7;$j++){
				
				$date = $this->data['start_day'] + $this->sek_in_day*$num++;
				$week_day = date('D', $date);
				$data['date'] = date('j',$date);
				
				$data['class'] = 'calCurrent';
				$tpl->tplSetNeeded('date/workind_day');
				
				
				
				if($this->isCurrentMonth($date)) {
					$data['class'] = 'calCurrent';
				} else {
					$data['class'] = 'calNotCurrent';
					if(!$this->show_other_days) {
						
					}
					
				}
				
				if($this->isToday($date)) { $data['class'] = 'calToday'; }
				
				$tpl->tplSetNested('week/date/event_item');
				$tpl->tplParse($data, 'week/date');
			}
			
			
			
			$tpl->tplSetNested('week/date');
			$tpl->tplParse('', 'week');
		}
		
		// week days, month, year
		$tpl->tplAssign('month_name', $this->month_name);
		$tpl->tplAssign('year_name', $this->year); 
		
		//$str = $_SERVER['PHP_SELF'].'?module='.$_GET['module'].'&page='.$_GET['page'];
		//$tpl->tplAssign('prev_link', $str.'&cal_date=;
		$tpl->tplAssign('next_link', $_SERVER['PHP_SELF'].'?action=print_schedule&from_calendar=true&day=1&month='.$this->next_month.'&year='.$this->next_year);
		
		
		$tpl->tplParse(array_merge($this->week_days,$GLOBALS['msg']));
		
		$tpl->tplPrint();
		
	}
		
		
/*
		$num_weeks = count($this->cur_month);
		$tpl->tplAssign('td_height', 90/$num_weeks.'%'); // td can vary
		
		foreach($this->cur_month as $week) {
			foreach($week as $k => $date) {
				$this->data['date'] = $date[0];
				$week_day = date('D', mktime(0,0,0,$date[1],$date[0],$date[2]));
				
				// not working day
				if(!in_array($week_day, $not_work_days[$doctor_id])){
					$tpl->tplSetNeeded('date/not_workind_day'); 
					$this->data['class'] = 'calNotWorkindDay';
					if($date[1] != $this->month) { $this->data['class'] = 'calNotCurrent'; } // not current month
				
				// current month
				} else { 
				
					$tpl->tplSetNeeded('date/workind_day'); 
					$this->data['class'] = 'calCurrent';
					$this->data['date_link'] = $_SERVER['PHP_SELF'].'?action=print_schedule&from_calendar=true&schedule_view=day&day='.$date[0].'&month='.$date[1].'&year='.$date[2];
					
					// date for appointment link
					$app_date = $this->prepareNum($date[2]).'-'.$this->prepareNum($date[1]).'-'.$this->prepareNum($date[0]); 
					
					// looking for event for the day
					$event_key = $date[1].$date[0];
					if(isset($events[$doctor_id][$event_key])) {
						$this->data['class'] = 'calEvent';
						
						foreach($events[$doctor_id][$event_key] as $k2 => $v2) {
							$v2['appointment_link'] = '\'appointment.php?action=update&schedule_id='.$v2['schedule_id'].'\','.$v2['schedule_id'].','.$doctor_id.',\''.$app_date.'\','.$v2['time'];	
							$v2['event_time'] = convert_time($v2['time']); // with pm
							$v2['other_info'] = $v2['room'] . '<br>Duration:' . minToHuman($v2['duration']); 
							$v2['div_num'] = 'd'.$v2['schedule_id'];
							$tpl->tplParse($v2, 'week/date/event_item');
						}
					}
					
					// not current month
					if($date[1] != $this->month) { $this->data['class'] = 'calNotCurrent'; } 
				}
				if($this->isToday($date[0],$date[1],$date[2])) { $this->data['class'] = 'calToday'; } // today
				
				$tpl->tplSetNested('week/date/event_item');
				$tpl->tplParse($this->data, 'week/date');
			
			}
			$tpl->tplSetNested('week/date');
			$tpl->tplParse('', 'week');
		}
		
		// week days, month, year
		$tpl->tplAssign('month_name', $this->month_name);
		$tpl->tplAssign('year_name', $this->year); 
		$tpl->tplAssign('prev_link', $_SERVER['PHP_SELF'].'?action=print_schedule&from_calendar=true&day=1&month='.$this->prev_month.'&year='.$this->prev_year);
		$tpl->tplAssign('next_link', $_SERVER['PHP_SELF'].'?action=print_schedule&from_calendar=true&day=1&month='.$this->next_month.'&year='.$this->next_year);
		$tpl->tplParse($this->week_days);
		
		$tpl->tplPrint();
	}
*/
}
require_once 'eleontev/e:/www/localhost/a_repository/ezactive/HTML/tplTemplatez.php';

$cal = &new CalendarUtil();
$cal->setCalendar();
$cal->setMonth();

echo "<pre>"; print_r($cal); echo "</pre>";
//$cal->monthView();
	
	
	
/*
$cal = new CalendarUtil();
$cal->setCalendar();
$month = $cal->setWeek();
$month = $cal->setMonth();

echo 'Start date: ' . date('d m Y', $month['start_day']); echo "<br>";
echo 'End date: ' . date('d m Y', $month['end_day']);	

echo "<br>";echo "<br>";
echo 'Perv: ' . date('d m Y', $month['prev']); echo "<br>";
echo 'Next: ' . date('d m Y', $month['next']);	


echo "<pre>"; print_r($month); echo "</pre>";
echo "<pre>"; print_r($cal); echo "</pre>";
*/
	
	

//1075064400
//1078002000

//1075582800

/*
for($i=0;$i<5;$i++){
	echo '---<br>';
	
	for($j=1;$j<=7;$j++){
		$date = 1075064400 + 86400*$j;
		echo date('d m Y',$date).'<br>';
	}
	
	
}
*/



/*




  	function setDay($time, $office_id) {
		
		for($i=$time[$office_id]['work_start'];$i<=$time[$office_id]['work_end'];$i+=$time[$office_id]['time_gap']){
			$i = adjust_time($i);
	        $this->cur_day[$i] = convert_time($i);			
		}
		
		//if(isset($time[$office_id]['break_start'])) {
		//	for($i=$time[$office_id]['break_start'];$i<=$time[$office_id]['break_end'];$i+=$time[$office_id]['time_gap']){
		//		$i = adjust_time($i);
	    //   		$this->office_break[$i] = convert_time($i);			
		//	}
		//}

		
		$this->time_gap = $time[$office_id]['time_gap'];
	}	




  function generateDay($doctors, $events = array(), $work_hours = array()) {
	
		$tpl = new tplTemplatez('template/schedule_day.html');
		$timestamp = $_SESSION['calendar_date'];
		$date = $this->fromTimestamp($timestamp); // array date['day'], ...
		$app_date = date('Y-m-d', $timestamp); // date for appointment link
			
		
		if(isset($_SESSION['doctor_filter'])) {
			foreach($doctors as $k => $v) {
				if(!in_array($v['doctor_id'], $_SESSION['doctor_filter'])) {
					unset($doctors[$k]);
				}
			}
		}
		
		// doctors names
		$num = ($a = count($doctors)) ? $a : 1;
		$doc_data['doctor_width'] = 100/$num;
		foreach($doctors as $k => $v) {
			$tpl->tplParse($v, 'doctor_name_row');	
		}
		
		// main row
		foreach($this->cur_day as $key_time => $val_time) {
		
			$this->data['time'] = $val_time;
			$this->data['class'] = (@$j++ & 1) ? 'trdarker' : 'trlighter';
			
			
			foreach($doctors as $k => $v) {	
				
				// very clever table formating td manipulation
				if(isset($rowspan[$v['doctor_id']])) { 
					if(@$rowspan[$v['doctor_id']] > @$temp[$v['doctor_id']]) {
						@$temp[$v['doctor_id']]++; 
						continue;
					} else {
						unset($rowspan[$v['doctor_id']]);
						unset($temp[$v['doctor_id']]);
					}
				}
				

				// defaults for doctor break
				$doctor_break = false;
				$doc_data['doctor_colspan'] = '1'; // to able - disable add link
				$doc_data['doctor_rowspan'] = '1'; // to able - disable add link
				$doc_data['class'] = '';
				
				$doc_data['date_link'] = $_SERVER['PHP_SELF'].'?action=print_schedule&from_calendar=true&schedule_view=day&day='.$date['day'].'&month='.$date['month'].'&year='.$date['year'];
				$doc_data['appointment_add_link'] = '\'appointment.php?action=add&date='.$app_date.'&time='.$key_time.'&doctor_id='.$v['doctor_id'].'\',0,'.$v['doctor_id'].',\''.$app_date.'\','.$key_time;

				
				// looking for event for the day
				if(isset($events[$v['doctor_id']][$key_time])) {
				
					foreach($events[$v['doctor_id']][$key_time] as $k2 => $v2) {
						
						$v2['appointment_link'] = '\'appointment.php?action=update&schedule_id='.$v2['schedule_id'].'\','.$v2['schedule_id'].','.$v['doctor_id'].',\''.$app_date.'\','.$v2['time'];
						
						// doctor break
						if($v2['service_id'] == 20000) {
							$doctor_break = true;
							$doc_data['doctor_colspan'] = '2';
							if($this->time_gap < $v2['duration']) {
								$doc_data['doctor_rowspan'] = ceil($v2['duration']/$this->time_gap);
								$rowspan[$v['doctor_id']] = $doc_data['doctor_rowspan'] - 1;
							}
						
							$doc_data['class'] = 'calNotWorkindDay';
							$v2['duration'] = minToHuman($v2['duration']);
							$v2['patient'] = '<b>UNAVAILABLE</b>'; 
							$v2['room'] = ''; 
					
						// appointment
						} else { 

							//$v2['event_time'] = convert_time($v2['time']); // with pm
							$v2['room'] = $v2['room'] . '<br>'; 
							$v2['duration'] = minToHuman($v2['duration']); 
							
							//$v2['div_num'] = 'd'.$v2['schedule_id'];
						}
					
						$tpl->tplParse($v2, 'row/row_doctor/event_item');
					}
				}		
			
				
				// doctor break or not working hour
				$work_hour = true; // by default all day is working hours
				if(isset($work_hours[$v['doctor_id']])) {
					$work_hour = (in_array($key_time, $work_hours[$v['doctor_id']])) ? true : false;
				}
				
				if($doctor_break == false && $work_hour == true) {
					$tpl->tplSetNeeded('row_doctor/workind_hours'); 					
				} else {
					$doc_data['doctor_colspan'] = '2';
					$doc_data['class'] = 'calNotWorkindDay';
				}
			
				$tpl->tplSetNested('row/row_doctor/event_item');
				$tpl->tplParse($doc_data, 'row/row_doctor');		
	
			} // <-- doctors loop end
			
			$tpl->tplSetNested('row/row_doctor');
			$tpl->tplParse($this->data, 'row');	
		}
		
		$prev = $this->fromTimestamp($timestamp - 86400); // array
		$next = $this->fromTimestamp($timestamp + 86400); // array
		
		$tpl->tplAssign('top_colspan', 1+(count($doctors)*2)-2); // colspan up row
		$tpl->tplAssign('prev_link', $_SERVER['PHP_SELF'].'?action=print_schedule&from_calendar=true&day='.$prev['day'].'&month='.$prev['month'].'&year='.$prev['year']);
		$tpl->tplAssign('next_link', $_SERVER['PHP_SELF'].'?action=print_schedule&from_calendar=true&day='.$next['day'].'&month='.$next['month'].'&year='.$next['year']);
		$tpl->tplAssign('cur_date', date('F d, Y (l)', $timestamp));
		
		$tpl->tplParse();	
		$tpl->tplPrint();
	}
  
  
  
  	function generateMonth($doctor_id, $events = array(), $not_work_days = array()) {
	
		$tpl = new tplTemplatez('template/schedule_month.html');	
		
		$num_weeks = count($this->cur_month);
		$tpl->tplAssign('td_height', 90/$num_weeks.'%'); // td can vary
		
		foreach($this->cur_month as $week) {
			foreach($week as $k => $date) {
				$this->data['date'] = $date[0];
				$week_day = date('D', mktime(0,0,0,$date[1],$date[0],$date[2]));
				
				// not working day
				if(!in_array($week_day, $not_work_days[$doctor_id])){
					$tpl->tplSetNeeded('date/not_workind_day'); 
					$this->data['class'] = 'calNotWorkindDay';
					if($date[1] != $this->month) { $this->data['class'] = 'calNotCurrent'; } // not current month
				
				// current month
				} else { 
				
					$tpl->tplSetNeeded('date/workind_day'); 
					$this->data['class'] = 'calCurrent';
					$this->data['date_link'] = $_SERVER['PHP_SELF'].'?action=print_schedule&from_calendar=true&schedule_view=day&day='.$date[0].'&month='.$date[1].'&year='.$date[2];
					
					// date for appointment link
					$app_date = $this->prepareNum($date[2]).'-'.$this->prepareNum($date[1]).'-'.$this->prepareNum($date[0]); 
					
					// looking for event for the day
					$event_key = $date[1].$date[0];
					if(isset($events[$doctor_id][$event_key])) {
						$this->data['class'] = 'calEvent';
						
						foreach($events[$doctor_id][$event_key] as $k2 => $v2) {
							$v2['appointment_link'] = '\'appointment.php?action=update&schedule_id='.$v2['schedule_id'].'\','.$v2['schedule_id'].','.$doctor_id.',\''.$app_date.'\','.$v2['time'];	
							$v2['event_time'] = convert_time($v2['time']); // with pm
							$v2['other_info'] = $v2['room'] . '<br>Duration:' . minToHuman($v2['duration']); 
							$v2['div_num'] = 'd'.$v2['schedule_id'];
							$tpl->tplParse($v2, 'week/date/event_item');
						}
					}
					
					// not current month
					if($date[1] != $this->month) { $this->data['class'] = 'calNotCurrent'; } 
				}
				if($this->isToday($date[0],$date[1],$date[2])) { $this->data['class'] = 'calToday'; } // today
				
				$tpl->tplSetNested('week/date/event_item');
				$tpl->tplParse($this->data, 'week/date');
			
			}
			$tpl->tplSetNested('week/date');
			$tpl->tplParse('', 'week');
		}
		
		// week days, month, year
		$tpl->tplAssign('month_name', $this->month_name);
		$tpl->tplAssign('year_name', $this->year); 
		$tpl->tplAssign('prev_link', $_SERVER['PHP_SELF'].'?action=print_schedule&from_calendar=true&day=1&month='.$this->prev_month.'&year='.$this->prev_year);
		$tpl->tplAssign('next_link', $_SERVER['PHP_SELF'].'?action=print_schedule&from_calendar=true&day=1&month='.$this->next_month.'&year='.$this->next_year);
		$tpl->tplParse($this->week_days);
		
		$tpl->tplPrint();
	}
	
	
	
	function generateWeek($doctors, $events = array(), $not_work_days = array()) {
	
		$tpl = new tplTemplatez('template/schedule_week.html');	
		
		if(isset($_SESSION['doctor_filter'])) {
			foreach($doctors as $k => $v) {
				if(!in_array($v['doctor_id'], $_SESSION['doctor_filter'])) {
					unset($doctors[$k]);
				}
			}
		}
		
		// doctors names
		$doc_data['doctor_width'] = 100/count($doctors);
		foreach($doctors as $k => $v) {
			$tpl->tplParse($v, 'doctor_name_row');	
		}
		
		// main row
		foreach($this->cur_week as $date) {
			$timestamp = mktime(0,0,0,$date[1],$date[0],$date[2]);
		
			$this->data['date'] = date('F d, Y', $timestamp); // date format
			$this->data['weekday'] = date('D', $timestamp);
			$this->data['class'] = (@$j++ & 1) ? 'trdarker' : 'trlighter';
			//$week_day = date('D',$timestamp);
			
			foreach($doctors as $k => $v) {
				
				// not workind day
				if(!in_array($this->data['weekday'], $not_work_days[$v['doctor_id']])) {
					$doc_data['doctor_colspan'] = 2;
					$doc_data['class'] = 'calNotWorkindDay';
							
				// workind day
				} else {
					$tpl->tplSetNeeded('row_doctor/workind_day'); 
					$doc_data['date_link'] = $_SERVER['PHP_SELF'].'?action=print_schedule&from_calendar=true&schedule_view=day&day='.$date[0].'&month='.$date[1].'&year='.$date[2];
					$doc_data['doctor_colspan'] = 1;
					$doc_data['class'] = '';
					
					// looking for event for the day
					$event_key = $date[1].$date[0];
					if(isset($events[$v['doctor_id']][$event_key])) {
						
						// date for appointment link
						$app_date = $this->prepareNum($date[2]).'-'.$this->prepareNum($date[1]).'-'.$this->prepareNum($date[0]); 
						
						foreach($events[$v['doctor_id']][$event_key] as $k2 => $v2) {
							$v2['appointment_link'] = '\'appointment.php?action=update&schedule_id='.$v2['schedule_id'].'\','.$v2['schedule_id'].','.$v['doctor_id'].',\''.$app_date.'\','.$v2['time'];	
							$v2['event_time'] = convert_time($v2['time']); // with pm
							$v2['other_info'] = $v2['room'] . '<br>Duration:' . minToHuman($v2['duration']); 
							$v2['div_num'] = 'd'.$v2['schedule_id'];
							$tpl->tplParse($v2, 'row/row_doctor/event_item');
						}
					}		
				}
				
				$tpl->tplSetNested('row/row_doctor/event_item');
				$tpl->tplParse($doc_data, 'row/row_doctor');		
			}
			
			if($this->isToday($date[0],$date[1],$date[2])) { $this->data['class'] = 'calToday'; } // today
			$tpl->tplSetNested('row/row_doctor');
			$tpl->tplParse($this->data, 'row');	
		}
		
		$prev = $this->fromTimestamp($this->week_start_timestamp - (86400*7)); // array
		$next = $this->fromTimestamp($this->week_start_timestamp + (86400*7)); // array
		
		$tpl->tplAssign('top_colspan', 2+(count($doctors)*2)-2); // colspan up row
		$tpl->tplAssign('prev_link', $_SERVER['PHP_SELF'].'?action=print_schedule&from_calendar=true&day='.$prev['day'].'&month='.$prev['month'].'&year='.$prev['year']);
		$tpl->tplAssign('next_link', $_SERVER['PHP_SELF'].'?action=print_schedule&from_calendar=true&day='.$next['day'].'&month='.$next['month'].'&year='.$next['year']);
		$tpl->tplAssign('start_date', date('F d, Y', $this->week_start_timestamp));
		$tpl->tplAssign('end_date', date('F d, Y', $this->week_start_timestamp+(86400*6)));
		
		$tpl->tplParse();	
		$tpl->tplPrint();
	}
  



class ScheduleEvents extends SheduleCalendar 
{
	
	var $room_filter_sql = '1=1';		// for use in SQL if nothind defined
	var $doctor_filter_sql = '1=1';		// for use in SQL if nothind defined
	var $service_filter_sql = '1=1';
	var $doctor_work_filter_sql = '1=1';
	
	var $own_param = '1=1';
	
	function ScheduleEvents($own_param = false) {
		if($own_param) { $this->own_param = $own_param; }
	}
	
	
	// for use in SQL WHERE rooms IN(1,2,3)
	function setRoomFilter($room_filter) {
		
		if($room_filter == 'no_rooms') {
			$this->room_filter_sql = "s.room_id='0'";
		} elseif($room_filter != 'all' && $room_filter) {
			$this->room_filter_sql = '(s.room_id='.$room_filter .' OR s.service_id=20000)';
		}
	}
	
	function setServiceFilter($service_filter) {
		if($service_filter != 'all' && $service_filter) {
			$this->service_filter_sql = '(s.service_id='.$service_filter .' OR s.service_id=20000)';
			//$room_filter = implode(',', $service_filter); // will be used in sql
			//$this->room_filter_sql = 's.service_id IN('.$service_filter.')';
		}
	}
	
	// for use in SQL WHERE doctor_id IN(1,2,3)
	function setDoctorFilter($doctor_filter) {
		
		if($doctor_filter) {
			$doctor_filter = implode(',', $doctor_filter); // will be used in sql
			$this->doctor_filter_sql = 's.doctor_id IN('.$doctor_filter.')';
			$this->doctor_work_filter_sql = 'employee_id IN('.$doctor_filter.')'; // for getWorkDays
		}
	}
	
	// for month
	function setDoctorFilterSingle($user_id, $doctor_id, $office_id) {
		
		// if user_id is a doctor or default doctor
		if(!$doctor_id) {
			$sql = "SELECT e.id FROM employee e, role r
        	WHERE e.id = '$user_id' AND r.as_doctor = 1 AND e.role_id = r.id";
			$result = mysql_query($sql) or die (db_error());
			
			// if user_id is a doctor SELECT it
			if(mysql_num_rows($result)) {
				//$row = mysql_fetch_assoc($result);
				$this->doctor_filter_id = $user_id;
				$this->doctor_filter_sql = 's.doctor_id = '.$user_id.'';
				$this->doctor_work_filter_sql = 'employee_id = '.$user_id.'';
			} 
			
			// default doctor
			else {
			
				$doctor = $this->getDoctors($office_id, true);
				$this->doctor_filter_id = $doctor[0]['doctor_id'];
				$this->doctor_filter_sql = 's.doctor_id = '.$doctor[0]['doctor_id'].'';
				$this->doctor_work_filter_sql = 'employee_id = '.$doctor[0]['doctor_id'].'';
			}
			
		// have doctor id
		} else {
			$this->doctor_filter_id = $doctor_id;
			$this->doctor_filter_sql = 's.doctor_id = '.$doctor_id.'';
			$this->doctor_work_filter_sql = 'employee_id = '.$doctor_id.'';
		} 
		
		return $this->doctor_filter_id;
	}
	
	
	// return doctors  
	// $for_date - in day view $_SESSION['calendar_date'] (timestamp)
	function getDoctors($office_id, $one_doctor = false,  $for_date = false, $own_param = '1=1') {
		
		$limit = ($one_doctor) ? 'LIMIT 1' : '';
		$for_date = ($for_date) ? 'w.num_day=' . (date('w', $for_date)+1) : '1=1'; // in day view
		$this->data = array();
		
		$sql = "SELECT DISTINCT e.id AS doctor_id, e.first_name, e.middle_name, e.last_name
		FROM employee e, role r, work_days w
		WHERE r.as_doctor = 1
		AND e.role_id = r.id
		AND e.id = w.employee_id
		AND w.office_id = '$office_id'
		AND {$for_date}
		AND {$own_param}
		{$limit}";
		//echo "<pre>"; print_r($sql); echo "</pre>";
		
		$result = mysql_query($sql) or die (db_error());
		while ($row = mysql_fetch_assoc($result)) {
			$this->data[] = array('doctor_id' => $row["doctor_id"],
							'doctor_name' => nameUpperCase($row["first_name"], $row['middle_name'], $row['last_name']));	
		}
		
		return $this->data;
	}
	
	
	// return shedule data for period FROM $start_date + $num_days
	function getScheduleEvents($office_id, $start_day, $end_day) {
		
		$i = 1; $day = 0; $schedule_data = array();
		$sql = "SELECT s.id AS schedule_id, s.doctor_id, s.duration,
		MONTH(s.date) AS event_month, DAYOFMONTH(s.date) AS event_day, s.time AS event_time, 
		ser.service, IF(s.room_id, r.name, 'no room') AS room,
		p.first_name, p.middle_name, p.last_name, p.work_phone
		FROM schedule s, patient p, services ser, employee e
		LEFT JOIN rooms r ON r.id = s.room_id
		WHERE s.office_id = '$office_id'
		AND e.id = s.doctor_id
		AND {$this->room_filter_sql}
		AND {$this->service_filter_sql}
		AND {$this->doctor_filter_sql}
		AND s.date BETWEEN '{$start_day}' AND '{$end_day}'
		AND s.patient_id = p.id
		AND s.service_id = ser.id
		AND {$this->own_param}
		ORDER BY s.doctor_id, event_day, event_time, s.id";
		//echo "<pre>"; print_r($sql); echo "</pre>";
		
		$result = mysql_query($sql) or die (db_error());
		while($row = mysql_fetch_assoc($result)){
			
			if($day == $row['event_day']){ ++$i; }
			else { $i = $i; }
			
			$schedule_key = $row['event_month'].$row['event_day'];
			$schedule_data[$row['doctor_id']][$schedule_key][$i] = 
							array('schedule_id' => $row['schedule_id'],
								  'time'     	=> $row['event_time'],
								  //'patient'		=> nameUpperCase($row['first_name'], $row['middle_name'], $row['last_name']),
								  'duration'	=> $row['duration'],
								  'service' 	=> $row['service'],
								  'room' 		=> $row['room']
								  );
														  
			$day = $row['event_day'];
		}
		
		//echo "<pre>"; print_r($schedule_data); echo "</pre>";
		return $schedule_data;
	}
	
	
	
	// return shedule data for period FROM $start_date + $num_days
	function getScheduleEventsDay($office_id, $date) {
		
		$i = 1; $day = 0; $schedule_data = array();
		$sql = "SELECT s.id AS schedule_id, s.doctor_id, s.duration,
		MONTH(s.date) AS event_month, DAYOFMONTH(s.date) AS event_day, s.time AS event_time, 
		ser.service, s.service_id, IF(s.room_id, r.name, 'no room') AS room,
		p.first_name, p.middle_name, p.last_name, p.work_phone
		FROM schedule s, services ser , employee e
		LEFT JOIN patient p ON p.id = s.patient_id
		LEFT JOIN rooms r ON r.id = s.room_id
		WHERE s.office_id = '$office_id'
		AND e.id = s.doctor_id
		AND {$this->room_filter_sql}
		AND {$this->service_filter_sql}
		AND {$this->doctor_filter_sql}
		AND s.date = '{$date}'
		AND s.service_id = ser.id
		ORDER BY s.doctor_id, event_day, event_time, s.id";
		//echo "<pre>"; print_r($sql); echo "</pre>";
		
		$result = mysql_query($sql) or die (db_error());
		while($row = mysql_fetch_assoc($result)){
			
			if($day == $row['event_time']){ ++$i; }
			else { $i = $i; }
			
			$schedule_data[$row['doctor_id']][$row['event_time']][$i] = 
							array('schedule_id' => $row['schedule_id'],
								  'service_id'	=> $row['service_id'],
								  'time'     	=> $row['event_time'],
								  'patient'		=> nameUpperCase($row['first_name'], $row['middle_name'], $row['last_name']),
								  'duration'	=> $row['duration'],
								  'service' 	=> $row['service'],
								  'room' 		=> $row['room']
								  );
														  
			$day = $row['event_time'];
		}
		
		//echo "<pre>"; print_r($schedule_data); echo "</pre>";
		return $schedule_data;
	}
	
	
	
	// return work days (array) for doctors
	function getWorkDays($office_id) {
		$days = array();
		$sql = "SELECT employee_id, num_day FROM work_days w
		WHERE {$this->doctor_work_filter_sql}
		AND office_id = '$office_id'";
		$result = mysql_query($sql) or die (db_error());
		$i = 1; $day = 0;
		while($row = mysql_fetch_assoc($result)){
			$days[$row['employee_id']][] = $this->weekday_name[$row['num_day']]; //array('Mon', 'Fri');
		}
		//echo "<pre>"; print_r($days); echo "</pre>";
		return $days;
	}
	
	
	function getWorkHours($office_id, $num_day, $time_settings) {
		
		//$time = Settings::getTimeSettings();
	
		//$time = Settings::getOfficeTimeSettings($office_id);
		
		
		$hours = array();
		$sql = "SELECT w.employee_id, o.time_gap,
		IF(wdh.work_start,  TIME_FORMAT(wdh.work_start, '%k%i'), TIME_FORMAT(o.work_start, '%k%i')) AS work_start,
		IF(wdh.work_end,    TIME_FORMAT(wdh.work_end, '%k%i'),    TIME_FORMAT(o.work_end, '%k%i')) AS work_end,
		IF(wdh.break_start, TIME_FORMAT(wdh.break_start, '%k%i'), TIME_FORMAT(o.break_start, '%k%i')) AS break_start,
		IF(wdh.break_end,   TIME_FORMAT(wdh.break_end, '%k%i'),   TIME_FORMAT(o.break_end, '%k%i')) AS break_end
		FROM work_days w, offices o
		LEFT JOIN work_days_hours wdh ON wdh.work_days_uid = w.uid
		WHERE {$this->doctor_work_filter_sql}
		AND o.id = w.office_id
		AND w.office_id = '$office_id'
		AND w.num_day = '$num_day'";
		$result = mysql_query($sql) or die (db_error());
		while($row = mysql_fetch_assoc($result)){
			
			//$work_end = 
			for($i=$row['work_start'];$i<$row['work_end'];$i+=$row['time_gap']){
				$i = adjust_time($i);
		       	if($i == $row['break_start'] || 
				  ($i > $row['break_start'] && $i < $row['break_end'])) { continue; } 
				$hours[$row['employee_id']][] = $i;
			}
		}
		//echo "<pre>"; print_r($hours); echo "</pre>";
		return $hours;
	}
	
	
	
}	
*/
?>